package com.mtk.launcher.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.lark.wifi.util.MyLog;
import com.mtk.launcher.R;
import com.mtk.launcher.activity.MainActivity;
import com.mtk.launcher.config.AppConfig;
import com.mtk.launcher.activity.SleepActivity;
import com.mtk.launcher.power.bean.TimeDealEntity;
import com.mtk.launcher.power.bean.TimeLocalEntity;
import com.mtk.launcher.power.util.CheckTimeUtil;
import com.mtk.launcher.power.util.PowerOnOffUtil;
import com.mtk.launcher.util.FileUtil;
import com.mtk.launcher.util.ScreenWakeUtil;
import com.mtk.launcher.util.SimpleDateUtil;
import com.mtk.launcher.util.TimerDealUtil;
import com.mtk.launcher.util.shared.SharedPerManager;
import com.mtk.launcher.view.LayoutViewBase;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyService extends Service {

    public static MyService instance;
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    ExecutorService executor = Executors.newFixedThreadPool(CPU_COUNT * 2);

    public void executor(Runnable runnable) {
        executor.execute(runnable);
    }

    public static MyService getInstance() {
        if (instance == null) {
            synchronized (MyService.class) {
                if (instance == null) {
                    instance = new MyService();
                }
            }
        }
        return instance;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                checkPowerOnOFF();
            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
                MyLog.cdl("屏幕状态=ACTION_SCREEN_ON=");
                ScreenWakeUtil.IS_SCREEN_STATE = true;
            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                MyLog.cdl("屏幕状态=ACTION_SCREEN_OFF=");
                ScreenWakeUtil.IS_SCREEN_STATE = false;
            }
        }
    };

    private Handler handler = new Handler();



    /***
     * 执行原则
     * 1. 没有打开开关，不执行
     * 2. 系统时间不对，不执行
     * 3. 没有保存数据，不执行
     * 4. 只有用户设置的数据，才执行定时开关屏
     */
    private void checkPowerOnOFF() {
        long currentTimeLong = SimpleDateUtil.getCurrentTimelONG();
        if (currentTimeLong < AppConfig.TIME_CHECK_POWER_REDUCE) {
            MyLog.powerOnOff("系统时间不对，不执行定时开关屏");
            return;
        }
        changePowerNofityAll();
        handler.removeCallbacks(runnableCheck);
        handler.postDelayed(runnableCheck, 3000);
    }

    Runnable runnableCheck = new Runnable() {
        @Override
        public void run() {
            dealCurrentScreenStatues();
        }
    };

    /***
     * 检查当前是亮屏还是暗屏状态
     */
    private void dealCurrentScreenStatues() {
        boolean isOnTime = CheckTimeUtil.checkCurrentIsOnOrOffTime();
        MyLog.powerOnOff("检查当前是否是开机时间==" + isOnTime);
        if (isOnTime) {
            //亮屏幕时间
            if (SleepActivity.isViewForst) {
                Intent intent = new Intent();
                intent.setAction(SleepActivity.EXIT_SLEEP_MODEL);
                sendBroadcast(intent);
            }
            return;
        }
        //去休眠
        if (SleepActivity.isViewForst) {
            Intent intent = new Intent();
            intent.setAction(SleepActivity.ENTER_SLEEP_MODEL);
            sendBroadcast(intent);
            return;
        }
        //暗屏 时间
        Intent intent = new Intent();
        intent.setClass(MyService.this, SleepActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initOther();
        initReceiver();
        resetPowerOnOffTime();
        initNotifyView();
    }

    private void initOther() {
        TimerDealUtil.getInstance().startToTimerMinRxJava();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                FileUtil.checkCrashLogFileSize(AppConfig.CRACH_PATH);
                FileUtil.checkCrashLogFileSize(AppConfig.LOG_PATH);
            }
        };
        executor(runnable);
    }

    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "persistent_notification_channel";

    private void initNotifyView() {
        // 创建通知渠道（Android 8.0+ 需要）
        createNotificationChannel();
        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification());
        startUpdateNotifyViewInfo();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        changePowerNofityAll();
        return START_STICKY;
    }

    PowerOnOffUtil powerOnOffUtil;

    /***
     * 是否更新定时开关机时间
     */
    private void changePowerNofityAll() {
        boolean enable = SharedPerManager.getPowerOnOffEnable();
        if (!enable) {
            return;
        }
        if (powerOnOffUtil == null) {
            powerOnOffUtil = new PowerOnOffUtil(MyService.this);
        }
        TimeDealEntity timeDealEntity = SharedPerManager.getPowerOnOffTime();
        if (timeDealEntity == null) {
            MyLog.powerOnOff("没有保存数据，不执行定时开关屏");
            powerOnOffUtil.changePowerOnOffByWorkModel("定时更新定时开关机数据");
            return;
        }
        long currentTimeLong = SimpleDateUtil.getCurrentTimelONG();
        long offTime = timeDealEntity.getOffTimeShow();
        long onTime = timeDealEntity.getOnTimeShow();
        MyLog.powerOnOff("定时检测=当前时间" + currentTimeLong + " /开机时间= " + onTime);
        if (currentTimeLong > onTime && currentTimeLong > offTime) {
            powerOnOffUtil.changePowerOnOffByWorkModel("检测当前时间大于下一次开机时间，开始制定下一组定时开关机");
        }
    }

    private void resetPowerOnOffTime() {
        List<TimeLocalEntity> entityList = PowerOnOffUtil.queryTimerList();
        if (entityList == null || entityList.size() < 1) {
            SharedPerManager.setPowerOnOffTime(null, "程序启动，检查没有定时，清理");
        }
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(receiver, filter);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        TimerDealUtil.getInstance().onDestroyTimer();
        // 停止前台服务并移除通知
        stopForeground(true);
    }


    //==下面的代码没有报错的情况下无需关注===================================================================================

    // 创建通知渠道（Android 8.0+）
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Persistent Notification",
                    NotificationManager.IMPORTANCE_LOW); // 低优先级，不打扰用户
            channel.setDescription("This is a persistent notification that cannot be dismissed");
            channel.setSound(null, null); // 无声音
            channel.enableVibration(false); // 无振动

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    // 创建通知
    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                        ? PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
                        : PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new Notification.Builder(this, CHANNEL_ID);
        } else {
            builder = new Notification.Builder(this);
        }
        return builder
                .setContentTitle(getString(R.string.title_notify))
                .setContentText(getString(R.string.content_notify) + System.currentTimeMillis())
                .setSmallIcon(R.mipmap.icon_app_launcher)
                .setContentIntent(pendingIntent)
                .setPriority(Notification.PRIORITY_LOW) // 低优先级
                .setOngoing(true) // 设置为常驻通知
                .build();
    }

    private void startUpdateNotifyViewInfo() {
        TimerDealUtil.getInstance().addGeneratorToList(new LayoutViewBase() {
            @Override
            public View getView() {
                return null;
            }

            @Override
            public void clearMemory() {

            }

            @Override
            public void timeChangeToUpdateView() {
                long currentTime = System.currentTimeMillis();
                updateNotification(getString(R.string.title_notify), getString(R.string.content_notify) + currentTime);
            }
        });
    }

    // 更新通知内容（可选）
    public void updateNotification(String title, String content) {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = createNotification();
        notification.extras.putCharSequence(Notification.EXTRA_TITLE, title);
        notification.extras.putCharSequence(Notification.EXTRA_TEXT, content);
        manager.notify(NOTIFICATION_ID, notification);
    }

}
